package com.birdboot.controller;

import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;
import java.net.URISyntaxException;

/**
 * 用于处理与用户数据相关业务的类
 */
public class UserController {
    private static File userDir;
    static{
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册");
        //1获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        if(username==null||username.isEmpty()||
           password==null||password.isEmpty()||
           nickname==null||nickname.isEmpty()||
           ageStr==null||ageStr.isEmpty()||
           !ageStr.matches("[0-9]{1,3}")){
            //重定向
            response.sendRedirect("/reg_info_error.html");
            return;
        }
        int age = Integer.parseInt(ageStr);

        User user = new User(username,password,nickname,age);

        File file = new File(userDir,username+".obj");
        //如果该文件已经存在，则说明本次为重复用户
        if(file.exists()){
            //跳转该用户已存在的提示页面
            response.sendRedirect("/have_user.html");
            return;
        }


        try(
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);

            //保存后跳转注册成功页面
            response.sendRedirect("/reg_success.html");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
